/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

/**
 * @author shubeta
 *
 */

import java.util.Map;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.sesame.toolkit.IdentifyCode;

public class IdentifyCodeController implements Controller {

    private IdentifyCode identifyCode;

    public void setIdentifyCode(IdentifyCode identifyCode) {
        this.identifyCode = identifyCode;
    }

    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 取出验证码
        Map code = identifyCode.generateImage();
        String sRand = (String) code.get("rand");
        BufferedImage image = (BufferedImage) code.get("image");

        // 将验证码存入SESSION
        HttpSession session = request.getSession();
        session.setAttribute("rand", sRand);

        // 输出图象到页面
        ServletOutputStream output = response.getOutputStream();
        ImageIO.write(image, "jpeg", output);
        output.close();
        return null;
    }

}